package com.bootdo.program.wallpaper.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.OssStorageDO;
import com.bootdo.common.oss.AttachFileService;
import com.bootdo.common.service.OssStorageService;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.program.wallpaper.domain.BzClassificationDO;
import com.bootdo.program.wallpaper.domain.BzConfigDO;
import com.bootdo.program.wallpaper.domain.BzWallpaperDO;
import com.bootdo.program.wallpaper.service.BzClassificationService;
import com.bootdo.program.wallpaper.service.BzConfigService;
import com.bootdo.program.wallpaper.service.BzWallpaperService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小程序壁纸表
 * 
 * @author guoyunfei
 * @email 2549789059@qq.com
 * @date 2021-07-08 15:48:09
 */
 
@Controller
@RequestMapping("/wallpaper/bzWallpaper")
public class BzWallpaperController  extends BaseController {

	private final String DIAGONAL = "/";

	@Autowired
	private BzWallpaperService bzWallpaperService;

	@Autowired
	private BzClassificationService bzClassificationService;

	@Autowired
	private AttachFileService attachFileService;
	@Autowired
	private BzConfigService bzConfigService;


	@Autowired
	private BootdoConfig bootdoConfig;

	@Autowired
	private OssStorageService ossStorageService;

	@Value("${spring.profiles.active}")
	private String active;

	@GetMapping("files")
	@RequiresPermissions("wallpaper:bzWallpaper:files")
	String files(Model model){
		Map<String,Object> map = new HashMap<>(4);
		map.put("enable",1);
		map.put("appid",isAdmin() ? null : (null == defaultAppid() ? "noData" : defaultAppid()));
		List<BzClassificationDO> cList = bzClassificationService.list(map);
		model.addAttribute("cList",cList);
		return "wallpaper/bzWallpaper/files";
	}

	@ResponseBody
	@GetMapping("/clazzList")
	public Object clazzList(){
		Map<String,Object> map = new HashMap<>(4);
		map.put("enable",1);
		map.put("appid",isAdmin() ? null : (null == defaultAppid() ? "noData" : defaultAppid()));
		List<BzClassificationDO> cList = bzClassificationService.list(map);
		return cList;
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wallpaper:bzWallpaper:files")
	public PageUtils list(@RequestParam Map<String, Object> params){
		List<BzConfigDO> oss_type = bzConfigService.getType("oss_type");
		params.put("appid",isAdmin() ? null : (null == defaultAppid() ? "noData" : defaultAppid()));
		//查询列表数据
        Query query = new Query(params);

		List<BzWallpaperDO> bzWallpaperList = bzWallpaperService.list(query);
		for (int i = 0; i < bzWallpaperList.size(); i++) {
			if(active.equals("pro") || active.equals("prod")){
				bzWallpaperList.get(i).setImage(oss_type.get(0).getValue() + bzWallpaperList.get(i).getImage());
			}else{
				bzWallpaperList.get(i).setImage(oss_type.get(0).getValue()+bzWallpaperList.get(i).getImage());
			}

		}
		int total = bzWallpaperService.count(query);
		PageUtils pageUtils = new PageUtils(bzWallpaperList, total);
		return pageUtils;
	}

	@ResponseBody
	@GetMapping("/list2")
	@RequiresPermissions("wallpaper:bzWallpaper:files")
	public PageUtils list2(@RequestParam Map<String, Object> params){
		params.put("appid",isAdmin() ? null : (null == defaultAppid() ? "noData" : defaultAppid()));
		//查询列表数据
		Query query = new Query(params);
		List<BzWallpaperDO> bzWallpaperList = bzWallpaperService.listTwo(query);
		int total = bzWallpaperService.count(query);
		PageUtils pageUtils = new PageUtils(bzWallpaperList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wallpaper:bzWallpaper:add")
	String add(){
	    return "wallpaper/bzWallpaper/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wallpaper:bzWallpaper:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		BzWallpaperDO bzWallpaper = bzWallpaperService.get(id);
		model.addAttribute("bzWallpaper", bzWallpaper);
	    return "wallpaper/bzWallpaper/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wallpaper:bzWallpaper:add")
	public R save( BzWallpaperDO bzWallpaper){
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if(null == defaultAppid()){
			return R.error("保存失败，请先配置小程序appid");
		}
		bzWallpaper.setAppid(defaultAppid());
		if(bzWallpaperService.save(bzWallpaper)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wallpaper:bzWallpaper:edit")
	public R update( BzWallpaperDO bzWallpaper){
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if(null == defaultAppid()){
			return R.error("保存失败，请先配置小程序appid");
		}
		bzWallpaper.setAppid(defaultAppid());
		bzWallpaperService.update(bzWallpaper);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wallpaper:bzWallpaper:remove")
	public R remove( Integer id){
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		BzWallpaperDO bzWallpaperDO = bzWallpaperService.get(id);
		bzWallpaperDO.setIsDelete(0);

		bzWallpaperService.update(bzWallpaperDO);
		return R.ok();
		/*
		List<BzConfigDO> config = bzConfigService.getType("upload_type");
		if("0".equals(config.get(0).getValue())){
			String fileName = bootdoConfig.getUploadPath() + bzWallpaperDO.getThumbnail().replace("/files/", "");
			boolean b = FileUtil.deleteFile(fileName);
			if (!b) {
				return R.error("数据库记录删除成功，文件删除失败");
			}
		}else if(config.get(0).getValue().equals("1")){
			attachFileService.deleteAliyun(bzWallpaperDO.getImage());
		}else{
			attachFileService.deleteQiniu(bzWallpaperDO.getImage());
		}

		if(bzWallpaperService.remove(id)>0){
			return R.ok();
		}
		return R.error();*/
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wallpaper:bzWallpaper:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		bzWallpaperService.batchRemove(ids);
		return R.ok();
	}

	@PostMapping("/upload/oss")
	@ResponseBody
	public R upload(@RequestParam("file") MultipartFile file,Integer classType,String className) throws Exception {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if(null == defaultAppid()){
			return R.error("上传失败，请先配置小程序appid");
		}
		if(null == classType){
			return R.error("请选择左侧栏目在进行上传");
		}

		List<BzConfigDO> config = bzConfigService.getType("upload_type");
		boolean equals = config.get(0).getValue().equals("1");
		String fileName = null;
		if("0".equals(config.get(0).getValue())){
			fileName = file.getOriginalFilename();

			String extName = cn.hutool.core.io.FileUtil.extName(fileName);
			fileName = IdUtil.simpleUUID() + "." + extName;

			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath() + DateUtil.format(new Date(), "yyyy/MM/"), fileName);

			if(active.equals("pro") || active.equals("prod")){
				//fileName = DIAGONAL+ DateUtil.format(new Date(), "yyyy/MM/") +fileName;
				fileName = DIAGONAL +fileName;
			}else{
				//fileName = "/files/"+ DateUtil.format(new Date(), "yyyy/MM/") +fileName;
				fileName = "/files/" +fileName;
			}

		}else if("1".equals(config.get(0).getValue())){
			fileName = DIAGONAL + attachFileService.uploadFileAliyun(file);
		}else{
			fileName = DIAGONAL + attachFileService.uploadFileQiniu(file);
		}
		BzWallpaperDO bzWallpaper = new BzWallpaperDO();
		bzWallpaper.setAppid(defaultAppid());
		bzWallpaper.setImage(fileName);
		bzWallpaper.setThumbnail(fileName);
		bzWallpaper.setClassId(classType);
		bzWallpaper.setTime(new Date());
		bzWallpaper.setCreateTime(new Date());
		bzWallpaper.setTags(className);
		bzWallpaperService.save(bzWallpaper);
		bzWallpaperService.saveAll(bzWallpaper);

		return R.ok().put("fileName",fileName);
	}

	@PostMapping("/upload/oss2")
	@ResponseBody
	public R upload(@RequestParam("file") MultipartFile file,Integer classType,String className,Integer ossId) throws Exception {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if(null == defaultAppid()){
			return R.error("上传失败，请先配置小程序appid");
		}

		if(null == ossId || ossId <= 0){
			return R.error("请选择存储方式");
		}

		if(null == classType){
			return R.error("请选择左侧栏目在进行上传");
		}


		OssStorageDO storageDO = ossStorageService.get(ossId);

		String fileName = null;
		if(!"阿里云".equals(storageDO.getOssStoragetype()) && !"七牛云".equals(storageDO.getOssStoragetype())){
			fileName = file.getOriginalFilename();

			String extName = cn.hutool.core.io.FileUtil.extName(fileName);
			fileName = IdUtil.simpleUUID() + "." + extName;

			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath() + DateUtil.format(new Date(), "yyyy/MM/dd/"), fileName);

			if(active.equals("pro") || active.equals("prod")){
				fileName = DIAGONAL+ DateUtil.format(new Date(), "yyyy/MM/dd/") +fileName;
			}else{
				fileName = "/files/"+ DateUtil.format(new Date(), "yyyy/MM/dd/") +fileName;
			}

		}else if("阿里云".equals(storageDO.getOssStoragetype())){
			fileName = DIAGONAL + attachFileService.uploadFileAliyun(file,storageDO);
		}else{
			fileName = DIAGONAL + attachFileService.uploadFileQiniu(file,storageDO);
		}
		BzWallpaperDO bzWallpaper = new BzWallpaperDO();
		bzWallpaper.setAppid(defaultAppid());
		bzWallpaper.setImage(fileName);
		bzWallpaper.setThumbnail(fileName);
		bzWallpaper.setClassId(classType);
		bzWallpaper.setTime(new Date());
		bzWallpaper.setCreateTime(new Date());
		bzWallpaper.setTags(className);
		bzWallpaper.setOssResourcesUrl(storageDO.getOssResourcesurl());
		bzWallpaper.setOssId(storageDO.getId());

		bzWallpaper.setImgSize(file.getSize());

		BufferedImage read = ImageIO.read(file.getInputStream());
		bzWallpaper.setImgWidth(read.getWidth());
		bzWallpaper.setImgHeight(read.getHeight());
		bzWallpaperService.save(bzWallpaper);
		bzWallpaperService.saveAll(bzWallpaper);

		return R.ok().put("fileName",fileName);
	}



}
